package com.ruoyi.web.controller.teaching;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.teaching.domain.TeachingClasses;
import com.ruoyi.teaching.domain.TeachingStudent;
import com.ruoyi.teaching.domain.TeachingStudentRecord;
import com.ruoyi.teaching.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teaching.domain.TeachingClassesStudents;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 班级学员Controller
 *
 * @author ruoyi
 * @date 2022-10-18
 */
@Controller
@RequestMapping("/teaching/students")
public class TeachingClassesStudentsController extends BaseController {
    private String prefix = "teaching/students";

    @Autowired
    private ITeachingClassesStudentsService teachingClassesStudentsService;

    @Autowired
    private ITeachingStudentService teachingStudentService;

    @Autowired
    private ITeachingStudentApplyService teachingStudentApplyService;

    @Autowired
    private ITeachingClassesService teachingClassesService;

    @Autowired
    private ITeachingStudentRecordService teachingStudentRecordService;

    @RequiresPermissions("teaching:students:view")
    @GetMapping()
    public String students() {
        return prefix + "/students";
    }

    /**
     * 查询班级学员列表
     */
//    @RequiresPermissions("teaching:students:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TeachingClassesStudents teachingClassesStudents) {
        startPage();
        List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(teachingClassesStudents);
        for (TeachingClassesStudents student : list) {
            Long studentId = student.getStudentId();
            Long schoolId = student.getSchoolId();
            Long classId = student.getClassId();
            student.setTeachingClasses(teachingClassesService.selectTeachingClassesByClassId(classId));
            student.setTeachingStudentApply(teachingStudentApplyService.selectTeachingStudentApplyByStudentIdAndSchoolId(studentId, schoolId));
            student.setTeachingStudent(teachingStudentService.selectTeachingStudentByStudentId(studentId));
        }
        return getDataTable(list);
    }

    /**
     * 导出班级学员列表
     */
    @RequiresPermissions("teaching:students:export")
    @Log(title = "班级学员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TeachingClassesStudents teachingClassesStudents) {
        List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(teachingClassesStudents);
        ExcelUtil<TeachingClassesStudents> util = new ExcelUtil<TeachingClassesStudents>(TeachingClassesStudents.class);
        return util.exportExcel(list, "班级学员数据");
    }

    /**
     * 新增班级学员
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存班级学员
     */
    @RequiresPermissions("teaching:students:add")
    @Log(title = "班级学员", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TeachingClassesStudents teachingClassesStudents) {
        return toAjax(teachingClassesStudentsService.insertTeachingClassesStudents(teachingClassesStudents));
    }

    /**
     * 调班学员
     */
    @PostMapping("/chgClassSave")
    @ResponseBody
    public AjaxResult chgClassSave(@RequestParam("classStudentId1") Long classStudentId, TeachingClassesStudents teachingClassesStudents) {
        Long classId = teachingClassesStudents.getClassId();
        Long studentId = teachingClassesStudents.getStudentId();
        TeachingClassesStudents param = new TeachingClassesStudents();
        param.setClassId(classId);
        param.setStudentId(studentId);
        param.setStatus("0");
        //通过 classId 和 studentId 找到班级学员
        List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(param);
        //判断找到的是否为空
        if (StringUtils.isNotEmpty(list)) {
            return error("该学员已存在要转的班级，无法调班");
        } else {
            //修改该学员在原班级的status
            TeachingClassesStudents orgStudent = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
            orgStudent.setStatus("1");
            teachingClassesStudentsService.updateTeachingClassesStudents(orgStudent);
            //记录为空 转入该班级该学员 或 在这个班级是已经转出 和 结班状态 可以转入该班级
            teachingClassesStudents.setCreateId(getUserId());
            teachingClassesStudents.setCreateBy(getLoginName());
            teachingClassesStudents.setCreateTime(new Date());
            teachingClassesStudentsService.insertTeachingClassesStudents(teachingClassesStudents);
            updateClasses(classId);
        }
        return success();
    }


    @PostMapping("/addList")
    @ResponseBody
    public AjaxResult addList(@RequestBody List<TeachingClassesStudents> ClassesStudents) {
        for (TeachingClassesStudents teachingClassesStudents : ClassesStudents) {
            teachingClassesStudents.setCreateId(getUserId());
            teachingClassesStudents.setCreateBy(getLoginName());
            teachingClassesStudents.setCreateTime(new Date());
            teachingClassesStudentsService.insertTeachingClassesStudents(teachingClassesStudents);
            updateClasses(teachingClassesStudents.getClassId());
        }
        return success();
    }

    /**
     * 修改班级学员
     */
    @RequiresPermissions("teaching:students:edit")
    @GetMapping("/edit/{classStudentId}")
    public String edit(@PathVariable("classStudentId") Long classStudentId, ModelMap mmap) {
        TeachingClassesStudents teachingClassesStudents = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
        mmap.put("teachingClassesStudents", teachingClassesStudents);
        return prefix + "/edit";
    }

    /**
     * 修改保存班级学员
     */
    @RequiresPermissions("teaching:students:edit")
    @Log(title = "班级学员", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TeachingClassesStudents teachingClassesStudents) {
        Long classId = teachingClassesStudents.getClassId();
        teachingClassesStudents.setUpdateBy(getLoginName());
        teachingClassesStudents.setUpdateTime(new Date());
        teachingClassesStudentsService.updateTeachingClassesStudents(teachingClassesStudents);
        updateClasses(classId);
        return success();
    }

    /**
     * 删除班级学员
     */
    @RequiresPermissions("teaching:students:remove")
    @Log(title = "班级学员", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        for (Long classStudentId : Convert.toLongArray(ids)) {
            TeachingStudentRecord param = new TeachingStudentRecord();
            param.setClassStudentId(classStudentId);
            List<TeachingStudentRecord> list = teachingStudentRecordService.selectTeachingStudentRecordList(param);
            if (StringUtils.isNotEmpty(list)) {
                return error("该学员有上课记录，无法删除!");
            }
            teachingClassesStudentsService.deleteTeachingClassesStudentsByClassStudentId(classStudentId);
            TeachingClassesStudents classesStudents = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
            updateClasses(classesStudents.getClassId());
        }
        return success();
    }

    /**
     * 修改班级人数
     */
    private void updateClasses(Long classId) {
        TeachingClasses classes = teachingClassesService.selectTeachingClassesByClassId(classId);
        if (StringUtils.isNotNull(classes)) {
            TeachingClassesStudents param = new TeachingClassesStudents();
            param.setClassId(classId);
            List<TeachingClassesStudents> totalStudents = teachingClassesStudentsService.selectTeachingClassesStudentsList(param);
            //统计该班级人数
            int classStudent = totalStudents.stream().filter(a -> a.getStatus().equals("0")).collect(Collectors.toList()).size();
            classes.setClassStudent(Convert.toLong(classStudent));
            teachingClassesService.updateTeachingClasses(classes);
        }
    }

    /**
     * 班级学员结班
     */
    @PostMapping("/endClass")
    @ResponseBody
    public AjaxResult endClass(Long classStudentId) {
        String status = "2";
        TeachingClassesStudents classesStudents = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
        classesStudents.setStatus(status);
        classesStudents.setUpdateBy(getLoginName());
        classesStudents.setUpdateTime(new Date());
        teachingClassesStudentsService.updateTeachingClassesStudents(classesStudents);
        updateClasses(classesStudents.getClassId());
        return success();
    }

    /**
     * 分配班级保存
     */
    @PostMapping("/allotClassSave")
    @ResponseBody
    public AjaxResult allotClassSave(@RequestBody List<TeachingClassesStudents> ClassesStudents) {
        for (TeachingClassesStudents teachingClassesStudents : ClassesStudents) {
            TeachingClassesStudents param = new TeachingClassesStudents();
            param.setClassId(teachingClassesStudents.getClassId());
            param.setStudentId(teachingClassesStudents.getStudentId());
            param.setStatus("0");
            List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(param);
            if (StringUtils.isNotEmpty(list)) {
                return error("该学员已存在要转的班级，无法分班");
            }
            teachingClassesStudents.setCreateId(getUserId());
            teachingClassesStudents.setCreateBy(getLoginName());
            teachingClassesStudents.setCreateTime(new Date());
            teachingClassesStudentsService.insertTeachingClassesStudents(teachingClassesStudents);
            updateClasses(teachingClassesStudents.getClassId());
        }
        return success();
    }
}
